#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版 View Specifications 按钮验证脚本
自动化验证，无需手动交互
"""

import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains

class SimpleViewSpecVerifier:
    """简化版 View Specifications 验证器"""
    
    def __init__(self):
        self.setup_driver()
        
    def setup_driver(self):
        """设置Chrome WebDriver"""
        chrome_options = Options()
        chrome_options.add_argument('--headless')  # 无头模式
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        
        service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.wait = WebDriverWait(self.driver, 10)
        self.actions = ActionChains(self.driver)
    
    def verify_buttons(self):
        """验证按钮"""
        try:
            print("🔍 开始验证 View Specifications 按钮 (无头模式)")
            
            # 访问页面
            url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
            print(f"📖 访问页面...")
            self.driver.get(url)
            time.sleep(8)  # 增加等待时间
            
            # 处理Cookie
            self.handle_cookies()
            time.sleep(3)
            
            # 获取所有车型
            car_elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
            print(f"🚗 找到 {len(car_elements)} 个车型元素")
            
            results = {}
            
            for i, car_element in enumerate(car_elements):
                car_name = car_element.get_attribute('data-cy')
                if not car_name:
                    continue
                    
                print(f"\n🔍 检查车型: {car_name}")
                
                # 检查可见性
                is_displayed = car_element.is_displayed()
                print(f"   可见性: {'可见' if is_displayed else '隐藏'}")
                
                button_found = False
                button_info = {}
                
                if is_displayed:
                    # 滚动到元素
                    self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", car_element)
                    time.sleep(1)
                    
                    # 悬停
                    self.actions.move_to_element(car_element).perform()
                    time.sleep(2)
                    
                    # 查找按钮的多种方法
                    button_methods = [
                        ('data-cy属性', 'button[data-cy="product-tile-overlay"]'),
                        ('ButtonAsLink类', 'button[class*="ButtonAsLink"]'),
                        ('文本匹配', None),  # 特殊处理
                        ('aria-hidden属性', 'button[aria-hidden="false"]')
                    ]
                    
                    for method_name, selector in button_methods:
                        if selector == None:
                            # 文本匹配方法
                            try:
                                buttons = self.driver.execute_script("""
                                    var buttons = arguments[0].querySelectorAll('button');
                                    var result = [];
                                    for (var i = 0; i < buttons.length; i++) {
                                        var btn = buttons[i];
                                        if (btn.textContent.includes('View Specifications') || 
                                            btn.textContent.includes('View') ||
                                            btn.textContent.includes('Specifications')) {
                                            result.push({
                                                text: btn.textContent.trim(),
                                                visible: btn.offsetParent !== null,
                                                dataCy: btn.getAttribute('data-cy'),
                                                className: btn.className
                                            });
                                        }
                                    }
                                    return result;
                                """, car_element)
                                
                                if buttons:
                                    print(f"   ✓ {method_name}: 找到 {len(buttons)} 个")
                                    for btn_info in buttons:
                                        print(f"      - 文本: '{btn_info['text']}'")
                                        print(f"      - data-cy: '{btn_info['dataCy']}'")
                                        print(f"      - 可见: {btn_info['visible']}")
                                    button_found = True
                                    button_info[method_name] = buttons
                                else:
                                    print(f"   ❌ {method_name}: 未找到")
                            except Exception as e:
                                print(f"   ❌ {method_name}: 出错 - {e}")
                        else:
                            # CSS选择器方法
                            try:
                                buttons = car_element.find_elements(By.CSS_SELECTOR, selector)
                                if buttons:
                                    visible_buttons = [btn for btn in buttons if btn.is_displayed()]
                                    print(f"   ✓ {method_name}: 找到 {len(buttons)} 个，可见 {len(visible_buttons)} 个")
                                    
                                    for btn in visible_buttons:
                                        text = btn.text.strip()
                                        data_cy = btn.get_attribute('data-cy')
                                        print(f"      - 文本: '{text}', data-cy: '{data_cy}'")
                                    
                                    if visible_buttons:
                                        button_found = True
                                        button_info[method_name] = len(visible_buttons)
                                else:
                                    print(f"   ❌ {method_name}: 未找到")
                            except Exception as e:
                                print(f"   ❌ {method_name}: 出错 - {e}")
                
                results[car_name] = {
                    'visible': is_displayed,
                    'button_found': button_found,
                    'button_methods': button_info
                }
            
            # 总结
            print(f"\n📊 验证结果总结:")
            print(f"="*50)
            
            total_cars = len(results)
            visible_cars = len([r for r in results.values() if r['visible']])
            found_buttons = len([r for r in results.values() if r['button_found']])
            
            print(f"总车型数: {total_cars}")
            print(f"可见车型: {visible_cars}")
            print(f"找到按钮: {found_buttons}")
            
            for car_name, result in results.items():
                status = "✅" if result['button_found'] else "❌"
                visibility = "可见" if result['visible'] else "隐藏"
                print(f"  {status} {car_name}: {visibility}")
                
                if result['button_found']:
                    for method, info in result['button_methods'].items():
                        print(f"      - {method}: {info}")
            
            # 保存结果
            with open('view_spec_verification.json', 'w', encoding='utf-8') as f:
                json.dump(results, f, indent=2, ensure_ascii=False)
            print(f"\n💾 结果已保存到 view_spec_verification.json")
            
            return results
            
        except Exception as e:
            print(f"❌ 验证过程出错: {e}")
            return {}
        finally:
            self.driver.quit()
    
    def handle_cookies(self):
        """处理Cookie"""
        try:
            self.driver.execute_script("""
                var cookieElements = document.querySelectorAll('[class*="cookie"], [class*="Cookie"], [class*="consent"]');
                cookieElements.forEach(function(el) {
                    el.style.display = 'none';
                });
            """)
            print(f"✓ Cookie处理完成")
        except Exception as e:
            print(f"❌ Cookie处理出错: {e}")

def main():
    """主函数"""
    verifier = SimpleViewSpecVerifier()
    results = verifier.verify_buttons()
    
    if results:
        found_count = len([r for r in results.values() if r['button_found']])
        visible_count = len([r for r in results.values() if r['visible']])
        
        print(f"\n🏁 验证完成！")
        print(f"找到按钮的车型: {found_count}/{visible_count}")
        
        if found_count == visible_count and visible_count > 0:
            print(f"🎉 所有可见车型的按钮都找到了！")
        elif found_count > 0:
            print(f"⚠️  部分车型找到了按钮，需要优化")
        else:
            print(f"❌ 没有找到任何按钮，需要重新分析选择器")

if __name__ == "__main__":
    main()
